<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

class Schema_Base {
	public static function clearValue($value) {
		return htmlspecialchars($value);
	}

	/**
	 * Return document info
	 */
	public static function getInfo($id, $fields = '*') {
		return Query::factory('select')
			->table('tbl_schemas')
			->fields($fields)
			->where('id=%d', $id)
			->limit(1)
			->execute()
			->row();
	}

	/**
	 * Return list of schemas
	 */
	public static function getList($status_id = 0) {
		$query = Query::factory('select')
			->table('tbl_schemas')
			->fields('*');
		
		if ($status_id > 0) {
			$query->where('status_id=%d', $status_id);
		} else {
			$query->where('status_id IN (1,2)', $status_id);			
		}
		
		$schemas = $query->orderBy('id', Query::ORDER_ASC)
			->execute()
			->rows();

		foreach ($schemas as &$schema) {
			$schema['name'] = self::getFileTitle($schema['file']);
		}

		return $schemas;
	}

	/**
	 * Return title of schema file
	 */
	public static function getFileTitle($file) {
		$result = $file;

		$schema_path = DATA_DIR . 'schemas/' . $file;
		if (file_exists($schema_path)) {
			$schema_xml = simplexml_load_file($schema_path);
			$root_node = $schema_xml->xpath('/schema');
			if ($root_node) {
				if (isset($root_node[0]['title'])) {
					$result = (string) $root_node[0]['title'];
				}
				if (isset($root_node[0]['title_' . Router::getLanguage()])) {
					$result = (string) $root_node[0]['title_' . Router::getLanguage()];
				}
			}
		}
		return $result;
	}

	/**
	 * Return title of schema file
	 */
	public static function getTitle($id) {
		$result = $id;
		$schema_info = self::getInfo($id, 'file');
		if ($schema_info) {
			$result = self::getFileTitle($schema_info['file']);
		}
		return $result;
	}

	/**
	 * Insert schema to database
	 */
	public static function insert($data) {
		return Query::factory('insert')
			->table('tbl_schemas')
			->data($data)
			->execute()
			->getLastId();
	}

	/**
	 * Update schema
	 */
	public static function update($id, $data) {
		$query = Query::factory('update')
			->table('tbl_schemas')
			->data($data)
			->where('id=%d', $id)
			->execute();

		return ($query->getAffectedRows() > -1);	
	}

	/**
	 * Delete schema
	 */
	public static function delete($id, $data) {
		$query = Query::factory('update')
			->table('tbl_schemas')
			->data($data)
			->where('id=%d', $id)
			->execute();

		return ($query->getAffectedRows() > -1);	
	}	
}
